package com.speed.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.catalina.tribes.util.UUIDGenerator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.speed.entity.Activiter;
import com.speed.entity.Activtites;
import com.speed.entity.MenberCardStartactBm;
import com.speed.entity.PersonInfo;
import com.speed.interceptor.ActivitesInterceptor;
import com.speed.service.ActiviterService;
import com.speed.service.MenberCardStarctBmService;
import com.speed.service.help.ActiviterImportHelper;
import com.speed.util.GenerationSerialNo;
import com.speed.util.StringUtils;
import com.speed.util.UuidGenerator;
import com.speed.util.ecxel.ExcelResolver;
import com.speed.util.ecxel.ImportTempData;
import com.speed.util.ecxel.TempData;
import com.speed.vo.ActiviterVO;

@Before(ActivitesInterceptor.class)
public class FileController extends Controller {

	private static List<ActiviterVO> errVos = new ArrayList<ActiviterVO>();
	private static List<ActiviterVO> rightVos = new ArrayList<ActiviterVO>();

	public void index() {
		renderJsp("offLineSign.jsp");
	}

	@Before({ POST.class })
	public void upload() {
		UploadFile file = getFile("excelFile");
		String isSkipStr = getAttr("isSkip");
		boolean isSkip = StrKit.isBlank(isSkipStr) ? false : "1".equals(isSkipStr) ? true : false;
		File source = file.getFile();
		String fileName = file.getFileName();
		String extension = fileName.substring(fileName.lastIndexOf("."));
		List<ImportTempData> importTempDatas = null;
		if (".xls".equals(extension) || ".xlsx".equals(extension)) {
			importTempDatas = makeExcelType();
		} else {
			// 如果不符合直接返回
			forwardAction("/activiter/content");
			return;
		}
		try {
			FileInputStream fis = new FileInputStream(source);
			List<TempData> tempDatas = ExcelResolver.importExcelData(fis, isSkip, importTempDatas);
			ActiviterImportHelper helper = importData(tempDatas);
			errVos = helper.getVosByStatus("0");
			rightVos = helper.getVosByStatus("1");
			source.delete();
			JSONObject json = new JSONObject();
			json.put("errInfos", errVos);
			json.put("rightInfos", rightVos);
			renderJson(json.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// forwardAction("/activiter/content");
	}

	/**
	 * 直接绑定数据到前端页面
	 * 
	 * @param tempDatas
	 * @return
	 */
	private ActiviterImportHelper importData(List<TempData> tempDatas) {
		Activtites activtites = (Activtites) getSession().getAttribute("activtites");
		ActiviterService activiterService = enhance(ActiviterService.class);
		errVos.clear();
		rightVos.clear();
		ActiviterImportHelper helper = new ActiviterImportHelper(tempDatas, activiterService,activtites.getInt(Activtites.ID));
		return helper;
	}

	private List<ImportTempData> makeExcelType() {
		List<ImportTempData> tempDatas = new ArrayList<ImportTempData>();

		ImportTempData tempData0 = new ImportTempData() {
			@Override
			public void inputData(Row row, TempData tempData) {
				Cell cell = row.getCell(0);
				if (cell == null) {
					tempData.setData("name", "");
					return;
				}
				int cellType = cell.getCellType();
				if (Cell.CELL_TYPE_STRING == cellType) {
					String mobile = cell.getStringCellValue();
					tempData.setData("name", StringUtils.replaceBlank(mobile));
				} else if (Cell.CELL_TYPE_NUMERIC == cellType) {
					Double mobile = cell.getNumericCellValue();
					tempData.setData("name", BigDecimal.valueOf(mobile).toPlainString());
				}
			}
		};
		ImportTempData tempData1 = new ImportTempData() {
			@Override
			public void inputData(Row row, TempData tempData) {
				Cell cell = row.getCell(1);
				if (cell == null) {
					tempData.setData("mobile", "");
					return;
				}
				int cellType = cell.getCellType();
				if (Cell.CELL_TYPE_STRING == cellType) {
					String mobile = cell.getStringCellValue();
					tempData.setData("mobile", StringUtils.replaceBlank(mobile));
				} else if (Cell.CELL_TYPE_NUMERIC == cellType) {
					Double mobile = cell.getNumericCellValue();
					tempData.setData("mobile", BigDecimal.valueOf(mobile).toPlainString());
				}
			}
		};
		tempDatas.add(tempData0);
		tempDatas.add(tempData1);
		return tempDatas;
	}

	/**
	 * 导入数据
	 */
	public void impt() {
		Date now = new Date();
		for (ActiviterVO vo : rightVos) {
			Activiter activiter = new Activiter();
			activiter.set(Activiter.ACTIVITER_NAME, vo.getName());
			activiter.set(Activiter.ACTIVITER_MOBILE, vo.getMobile());
			activiter.set(Activiter.SIGN_CODE, GenerationSerialNo.generNo());
			activiter.set(Activiter.SIGN_STATUS, Boolean.FALSE);
			Activtites activtites = (Activtites) getSession().getAttribute("activtites");
			activiter.set(Activiter.ACTIVITES_ID, activtites != null ? activtites.get(Activtites.ID) : null);
			// 默认为未支付
			activiter.set(Activiter.IS_PAY, Boolean.FALSE);
			activiter.set(Activiter.HD_ID, activtites != null ? activtites.get(Activtites.WXACT_ID) : null);
			activiter.save();

			MenberCardStarctBmService bmService = enhance(MenberCardStarctBmService.class);
			List<String> whereCodis = new ArrayList<String>();
			Ret ret = new Ret();
			ret.put(MenberCardStartactBm.RECORD_ID, activiter.get(Activiter.HD_ID));
			whereCodis.add(MenberCardStartactBm.RECORD_ID);
			ret.put(MenberCardStartactBm.MP, activiter.get(Activiter.ACTIVITER_MOBILE));
			whereCodis.add(MenberCardStartactBm.MP);
			// 暂时不联合姓名一起查
			// ret.put(MenberCardStartactBm.NAME,
			// activiter.get(Activiter.ACTIVITER_NAME));
			MenberCardStartactBm bm = bmService.findMenberCardStarctBmForOne(ret, whereCodis, MenberCardStartactBm.MP);
			if (bm == null) {
				MenberCardStartactBm newBm = new MenberCardStartactBm();
				newBm.set(MenberCardStartactBm.MP, activiter.get(Activiter.ACTIVITER_MOBILE));
				newBm.set(MenberCardStartactBm.NAME, activiter.get(Activiter.ACTIVITER_NAME));
				newBm.set(MenberCardStartactBm.ORDERNUM, activiter.get(Activiter.SIGN_CODE));
				newBm.set(MenberCardStartactBm.RECORD_ID, activiter.get(Activiter.HD_ID));
				newBm.set(MenberCardStartactBm.BM_TIME, now);
				newBm.save();
			}
		}
		renderText("完成导入数据 ！");
	}

}